<template>
<div>
  <s-container @search="handleQuery" @reset="handleQueryReset" :loading="loading">
        <template #searchForm>
            <n-form ref="searchRef" :label-width="80" :model="searchForm.value" label-placement="left" inline>
                <n-form-item label="角色名" path="roleName" class="fi-w">
                    <n-input v-model:value="searchForm.value.roleName" clearable  @keyup.enter.native="handleQuery" />
                </n-form-item>
            </n-form>
        </template>
        <template #btnBar>
					<s-bar-add-btn @click="handleAddClick" v-permission="['system:role:add']"></s-bar-add-btn>
					<s-bar-del-btn :disabled="!(checkRows && checkRows.length>0)" :click="handleDeleteListPositive" v-permission="['system:role:remove']"></s-bar-del-btn>
          <TableColumnSetting v-model:columns="columns" />
        </template>
				<template #toolBar>

				</template>
        <template #dataTable>
                <s-data-table :list="list" v-model:pageObj="pageObj" :columns="columns" :loading="loading"
                :checked-row-keys="checkRows.map(it=>it.id)"
                @update:checked-row-keys="handleCheck" />
        </template>
      </s-container>
      <slef-form  v-model:visible="showModal" :operate-type="editKey == null?'add' : 'edit'" :editKey="editKey" @submitted="handleSubmitted" ></slef-form>

</div>


</template>

<script  setup lang='tsx' >
import { ref, onMounted,Ref } from 'vue';
import { DataTableColumns, NSpace, FormInst, NButton } from 'naive-ui';
import { usePageList } from '@/hooks';
import { isBusinessYse } from '@/utils/common'
import { fetchRolePage,fetchRemoveRoles,fetchRole,fetchUpdateRoleStatus } from '@/service/api/sys/role'
import PopconfirmBtn from "~/src/components/custom/popconfirm-btn.vue"
import SRowEditBtn from "~/src/components/custom/s-row-edit-btn.vue"
import SRowDelBtn from "~/src/components/custom/s-row-del-btn.vue"
import SContainer from "~/src/components/custom/s-container.vue"
import SDataTable from "~/src/components/custom/s-data-table.vue"
import slefForm from "./form.vue"
import { BusinessStatus } from '~/src/enum';
interface DataSource extends SysAuth.RoleInfo { }
interface SearchForm { roleName?: string | null }
const columns: Ref<DataTableColumns<DataSource>> = ref([
    {
        type: "selection"
    },
    {
        title: '角色名',
        key: 'roleName',
        align: 'center',
    },
    {
        title: '角色标识符',
        key: 'roleKey',
        align: 'center',
    },
    {
        title: '状态',
        key: 'status',
        align: 'center',
        render (rowData: DataSource){
            const status = rowData.status
            const statusStr = isBusinessYse(status) ? "启用" : "禁用"
            const transStatusStr = isBusinessYse(status)  ? "禁用" : "启用"
            const btnType = isBusinessYse(status)  ? "success" : "warning"
            return <>
								<PopconfirmBtn type={btnType} ghost="true" size="small"	btnStr={statusStr}  confirmText={`是否确定${transStatusStr}当前角色`}
								onPositiveClick={()=>handleChangeRowStatus(rowData)}></PopconfirmBtn>
							</>
        }
    },
    {
        title: "操作列",
        key: "",
        align: 'center',
        width: 200,
        fixed: 'right',
        render(rowData: DataSource) {
            return <>
						<NSpace justify="center">
							<SRowEditBtn v-permission={['system:role:edit']} onClick={ () => handleEditClick(rowData) } ></SRowEditBtn>
							<SRowDelBtn v-permission={['system:role:remove']} click={ () => handleDeletePositive(rowData) }  ></SRowDelBtn>
							</NSpace>
						</>
        }
    }
]) as Ref<DataTableColumns<DataSource>>;

const searchRef = ref<FormInst | null>(null)
const checkRows = ref<DataSource[]>([]);
  const editKey = ref<Common.IdType | null>(null)
const {
	loading,
	searchForm,
	list,
	pageObj,
	getList,
	handleQueryReset,
	handleQuery
 } = usePageList<DataSource>(
	initSearchFormData,
	fetchRolePage,
	()=>{
		checkRows.value=[]
	},
	undefined
);


const showModal = ref(false);


function initSearchFormData():SearchForm{
    return { roleName: null }
}

function handleCheck(keys: Array<string | number>, rows: DataSource[]) {
    checkRows.value = rows
}

async function handleDeleteListPositive(){
    await fetchRemoveRoles(checkRows?.value.map(it=>it.id!))
    getList()
    return true;
}
async function handleDeletePositive(row:DataSource):Promise<boolean> {
    if(!row || !row.id){
        window.$message?.error("数据id异常,请刷新后重试")
        return false
    }
    await fetchRemoveRoles([row.id])
    getList()
    return true
}
async function handleChangeRowStatus(row:DataSource){
    const updateStatus = row.status == BusinessStatus.Yes ? BusinessStatus.No : BusinessStatus.Yes
    const { error } = await fetchUpdateRoleStatus(row.id!,updateStatus)

    if(!error)
        window.$message?.success("操作成功")
    getList()
}


async function handleEditClick(row: DataSource) {
    if(!row || !row.id){
        window.$message?.error("当前行数据异常,请刷新后重试")
        return;
    }
    editKey.value = row.id;
    showModal.value = true;

}
function handleSubmitted(){
  editKey.value = null
  getList()
}
function handleAddClick(){
    showModal.value = true;
}

onMounted(() => {
    getList()
})
</script>

<style lang='scss' scoped>
</style>
